﻿using System.Collections.Generic;
using System.Threading.Tasks;
using org.apache.zookeeper;

namespace ESoft.Zookeeper
{
    public class ZooKeeperService : IZooKeeperService
    {
        private readonly ZookeeperClient _zookeeperClient;

        public ZooKeeperService(ZookeeperClient zookeeperClient)
        {
            _zookeeperClient = zookeeperClient;
        }
        public async Task CreateEphemeralAsync(string path, byte[] data)
        {
            await _zookeeperClient.CreateAsync(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        }

        public async Task CreatePersistentAsync(string path, byte[] data)
        {
            await _zookeeperClient.CreateAsync(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }

        public async Task CreateRecursiveAsync(string path, byte[] data)
        {
            var paths = path.Substring(1).Split('/');
            foreach (var p in paths)
            {
                if(!await ExistsAsync($"/{p}"))
                {
                    await _zookeeperClient.CreateAsync($"/{p}", data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                }
               
            }
          //  await _zookeeperClient.Se(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }

        public async Task DeleteAsync(string path)
        {
            await _zookeeperClient.DeleteAsync(path);
        }

        public async Task<bool> ExistsAsync(string path)
        {
            var stat = await _zookeeperClient.ExistsAsync(path);
            return stat!=null&&stat.getDataLength() > 0;
        }

        public async Task<IEnumerable<string>> GetChildrenAsync(string path)
        {
            var result = await _zookeeperClient.GetChildrenAsync(path);
            return result.Children;
        }

        public async Task<IEnumerable<byte>> GetDataAsync(string path)
        {
            var result = await _zookeeperClient.GetDataAsync(path);
            return result.Data;
        }
    }
}
